package handler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;

import javax.swing.JProgressBar;
import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import parser.CmmLexer;
import parser.CmmParser;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import ir.*;
import ui.EditorFrame;
//import util.CommandUtil;

//运行cmm文件处理类
public class CmmRunHandler {

	
	public String run(EditorFrame editorFrame) {
		try {
			//获得项目目录的路径
			//String projectPath = editorFrame.getCurrentProject().getAbsolutePath();
			//获得源文件的全路径
			//String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			//拼装命令
			//String command ="java -jar F:\\workspace\\cmmwithide\\out\\artifacts\\cmmwithide_jar\\cmmwithide.jar F:\\workspace\\cmmwithide\\TestCases\\test1_变量声明.cmm " ;
			//Process p = CommandUtil.executeCommand(command);
			//String result = CommandUtil.exeCmd(command);
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			
			System.setOut(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output.txt")));
			ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(sourcePath));
			CmmLexer cl=new CmmLexer(input);
			CmmParser parser=new CmmParser(new CommonTokenStream(cl));
			ParseTree rule=parser.program();
			ParseTreeWalker walker=new ParseTreeWalker();
            IRProduceListener IR = new IRProduceListener();
			walker.walk(IR,rule);
            IRExecuter EX = new IRExecuter(IR.Code);
            EX.excute();
            
            String result = "";
            try{
                BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output.txt"));//构造一个BufferedReader类来读取文件
                String s = null;
                while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                    result=result+s+"\n";
                }
                br.close();    
            }catch(Exception e){
                e.printStackTrace();
            }
            
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);  
	        new Thread(){  
	            public void run(){  
	                progressBar.setValue(100);  
	                 
	                progressBar.setString("完成");  
	            }  
	        }.start(); 
			return result;
		} 
		catch (Exception e) {
			return e.getMessage();
		}
	}
	
	public String LexicalAnalysis(EditorFrame editorFrame){
		try{
			//获得源文件的全路径
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			String result = "";
			FileInputStream is = new FileInputStream(sourcePath);
			ANTLRInputStream input = new ANTLRInputStream(is);
			CmmLexer lexer = new CmmLexer(input);
			List list=lexer.getAllTokens();
			Iterator<CommonToken> iterator = list.iterator();
			while(iterator.hasNext()){
				CommonToken token = iterator.next();
				result = result + "Line "+token.getLine()+"   "+lexer.ruleNames[token.getType()-1]+"   "+token.getText()+"\n";
			}
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);  
	        new Thread(){  
	            public void run(){  
	            	progressBar.setValue(100);  
	                 
	                progressBar.setString("完成");  
	            }  
	        }.start(); 
			return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
	
	public String SynaticalAnalysis(EditorFrame editorFrame){
		try{
			//获得源文件的全路径
			String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
			String result = "";
			FileInputStream is = new FileInputStream(sourcePath);
			ANTLRInputStream input = new ANTLRInputStream(is);
			CmmLexer lexer = new CmmLexer(input);
			CommonTokenStream tokens = new CommonTokenStream(lexer);
			//List list=lexer.getAllTokens();
			CmmParser parser = new CmmParser(tokens);
			ParseTree tree = parser.program();
			result = tree.toStringTree(parser);
			//parser.prog();
			//result = parser.visit();
			JProgressBar progressBar = editorFrame.getProgressBar();
			progressBar.setStringPainted(true);  
	        new Thread(){  
	            public void run(){  
	            	progressBar.setValue(100);  
	                progressBar.setString("完成");  
	            }  
	        }.start(); 
			return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
	public String irProduce(EditorFrame editorFrame){
		//获得源文件的全路径
		try{
		String sourcePath = editorFrame.getCurrentFile().getFile().getAbsolutePath();
		String result = "";
			
		FileInputStream is = new FileInputStream(sourcePath);
		ANTLRInputStream input = new ANTLRInputStream(is);
		System.setOut(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output1.txt")));
		System.setErr(new PrintStream(new FileOutputStream("F:\\workspace\\cmmwithide\\out\\output2.txt")));
		CmmLexer cl=new CmmLexer(input);
		CmmParser parser=new CmmParser(new CommonTokenStream(cl));
		ParseTree rule=parser.program();
		ParseTreeWalker walker=new ParseTreeWalker();
		IRProduceListener irListener = new IRProduceListener();
			
			
		walker.walk(irListener,rule);
		Iterator<IRLine> ir = irListener.Code.iterator();
			
		IRLine line;
		while(ir.hasNext()){
			line = ir.next();
			result = result + line.toString()+"\n";
		}
			
			
		if(result.equals("")){
			String result1 = "";
	        try{
	            BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output2.txt"));//构造一个BufferedReader类来读取文件
	            String s = null;
	            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
	                result1=result1+s+"\n";
	            }
	        br.close(); 
	        return result1;
	        }catch(Exception e){
	            e.printStackTrace();
	        }
		}
		else{
			System.out.println(result);
			String result2 = "";
	        try{
	            BufferedReader br = new BufferedReader(new FileReader("F:\\workspace\\cmmwithide\\out\\output1.txt"));//构造一个BufferedReader类来读取文件
	            String s = null;
	            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
	            	result2=result2+s+"\n";
	            }
	            br.close(); 
	            return result2;
	        }catch(Exception e){
	            e.printStackTrace();
	        }
		}
			
		JProgressBar progressBar = editorFrame.getProgressBar();
		progressBar.setStringPainted(true);
		new Thread(){
			public void run(){
				progressBar.setValue(100);
				progressBar.setString("完成");
			}
		}.start();
		return result;
		}catch(Exception e){
			return e.getMessage();
		}
	}
}

